package com.tang.commodity.controller;

import com.tang.commodity.entity.Goods;
import com.tang.commodity.service.GoodsService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/*
 *文件名: GoodsController
 *创建者: 醉意丶千层梦
 *创建时间:2021/12/13 13:16
 *描述: 这是一个示例
 */
@RestController
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    private static Logger logger = LogManager.getLogger(GoodsController.class);

    @ResponseBody
    @RequestMapping(value = "/goods/insert",method = RequestMethod.POST)
    public int insertGoods(@RequestBody Goods goods){
        if (goods==null || goods.getNo()==null ||goods.getNo().isEmpty()){
            logger.error("insert goods error");
            return -1;
        }
        logger.info("insert goods :"+ goods);
        return goodsService.insertGoods(goods);
    }

    @ResponseBody
    @RequestMapping(value = "/goods/delete",method = RequestMethod.POST)
    public int deleteGoods(String no){
        if (no==null || no.isEmpty()){
            logger.error("delete goods error");
            return -1;
        }
        logger.info("delete no : "+ no);
        goodsService.deleteGoods(no);
        return 1;
    }

    @ResponseBody
    @RequestMapping(value = "/goods/update",method = RequestMethod.POST)
    public int updateGoods(@RequestBody Goods goods){
        if (goods==null || goods.getNo()==null ||goods.getNo().isEmpty()){
            logger.error("update goods error");
            return -1;
        }
        logger.info("update goods : "+ goods);
        return goodsService.updateGoods(goods);
    }

    @ResponseBody
    @RequestMapping(value = "/goods/search",method = RequestMethod.POST)
    public List<Goods> searchGoods(String  key){
        if (key==null)
            key="";
        logger.info("search goods for: "+ key);
        return goodsService.searchGoods(key);
    }

    @RequestMapping(value = "/goods/image",method = RequestMethod.GET)
    public void download(String fileName, HttpServletRequest request, HttpServletResponse response){
        //服务器文件路径
//        String path=System.getProperty("user.dir")+"/classes/image/"+imageName;

        //测试路径
        String path="./src/main/resources/image/"+fileName;
        logger.info("download image with filePath : "+ path);

        if (path != null) {
            File file = new File(path);
            if (file.exists()) {
                File[] fileList=file.listFiles();
                if (fileList.length>0){
                    File tmp =fileList[0];
                    response.setContentType("application/force-download");// 设置强制下载不打开
                    response.addHeader("Content-Disposition",
                            "attachment;fileName=" + fileName);// 设置文件名
                    byte[] buffer = new byte[1024];
                    FileInputStream fis = null;
                    BufferedInputStream bis = null;
                    try {
                        fis = new FileInputStream(tmp);
                        bis = new BufferedInputStream(fis);
                        OutputStream os = response.getOutputStream();
                        int i = bis.read(buffer);
                        while (i != -1) {
                            os.write(buffer, 0, i);
                            i = bis.read(buffer);
                        }
                        logger.info("download image success : "+ path);

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (bis != null) {
                            try {
                                bis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
            else {
                logger.info("does not exist : "+ path);
            }
        }

    }

    @ResponseBody
    @RequestMapping(value = "/goods/upload",method = RequestMethod.POST)
    public String logUpload(@RequestParam("file") MultipartFile file[],@RequestParam("fileName") String fileName) throws Exception {
        if (file == null || file.length==0) {
            System.out.println("文件为空");
            return "false";
        }

        //服务器存储路径
        //String path = System.getProperty("user.dir")+"/classes/image";

        //测试路径
        String path="./src/main/resources/image/"+fileName;
        logger.info("upload image with filePath : "+ path);
        File tmp = new File(path);
        if(!tmp.isDirectory()){
            tmp.mkdirs();
        }

        for (int i=0;i<file.length;i++){
            try {
                //构建真实路径
                File newFile = new File(tmp.getAbsolutePath() + File.separator + file[i].getOriginalFilename());
                logger.info("image save with : "+ newFile.getAbsolutePath());
                //上传到绝对路径
                file[i].transferTo(newFile);
                logger.info("The file "+(i+1)+" was uploaded successfully");
            } catch (IOException e) {
                logger.info("The file "+(i+1)+" was uploaded error "+e.getMessage());
                return "false！";
            }
        }
        return "success";
    }

}
